"""
编辑任务对话框
"""
from PyQt6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel,
                           QLineEdit, QPushButton, QMessageBox, QComboBox, QFrame, QWidget, QApplication)
from PyQt6.QtCore import Qt, pyqtSignal
import json
from com.db.task_manager import TaskManager
from com.db.profit_rate_price_manager import ProfitRatePriceManager
from com.constants.wear_ranges import (WearCategory, get_wear_ranges, 
                                     get_category_by_wear, WEAR_CATEGORY_NAMES)

class EditTaskDialog(QDialog):
    """编辑任务对话框"""
    
    task_updated = pyqtSignal()
    
    def __init__(self, task, task_manager, parent=None):
        super().__init__(parent)
        self.task = task
        self.task_manager = task_manager
        self.profit_rate_price_manager = ProfitRatePriceManager()  # 初始化利润率价格变动记录管理器
        
        # 初始化状态变量
        self.is_updating_profit_rate = False
        self.is_updating_scan_price = False
        
        # 阻止回车键关闭对话框
        self.setModal(True)
        # Qt.Key_Return和Qt.Key_Enter不作为默认按键
        self.setWindowFlags(self.windowFlags() & ~Qt.WindowType.WindowContextHelpButtonHint)
        
        # 调试输出
        print(f"初始化 EditTaskDialog, 任务ID: {self.task.get('id')}")
        print(f"任务目标售价: {self.task.get('target_sell_price')}")
        print(f"任务利润率: {self.task.get('profit_rate')}")
        print(f"任务扫货价: {self.task.get('buy_price_limit')}")
        
        # 初始化 UI
        self.setup_ui()
    
    def setup_ui(self):
        """初始化UI"""
        self.setWindowTitle("编辑任务")
        self.setFixedSize(400, 400)
        
        layout = QVBoxLayout(self)
        layout.setContentsMargins(20, 20, 20, 20)
        layout.setSpacing(20)
        
        # 商品信息（只读）
        info_layout = QVBoxLayout()
        
        # 商品ID
        id_layout = QHBoxLayout()
        id_label = QLabel("商品ID：")
        id_label.setStyleSheet("font-size: 14px;")
        id_value = QLabel(str(self.task['goods_id']))
        id_value.setStyleSheet("font-size: 14px;")
        id_layout.addWidget(id_label)
        id_layout.addWidget(id_value)
        id_layout.addStretch()
        info_layout.addLayout(id_layout)
        
        # 商品名称
        name_layout = QHBoxLayout()
        name_label = QLabel("商品名称：")
        name_label.setStyleSheet("font-size: 14px;")
        name_value = QLabel(self.task['name'])
        name_value.setStyleSheet("font-size: 14px;")
        name_layout.addWidget(name_label)
        name_layout.addWidget(name_value)
        name_layout.addStretch()
        info_layout.addLayout(name_layout)
        
        # 磨损度选择
        wear_layout = QHBoxLayout()
        wear_label = QLabel("磨损度：")
        wear_label.setStyleSheet("font-size: 14px;")
        self.wear_combo = QComboBox()
        self.wear_combo.setStyleSheet("""
            QComboBox {
                font-size: 14px;
                padding: 5px;
                min-width: 150px;
            }
        """)
        
        # 获取当前任务的外观和磨损范围
        filter_conf = {}
        try:
            filter_conf_str = self.task.get('filter_conf', '{}')
            filter_conf = json.loads(filter_conf_str) if isinstance(filter_conf_str, str) else filter_conf_str
        except (json.JSONDecodeError, TypeError):
            pass
            
        current_min_wear = float(filter_conf.get('min_paintwear', '0'))
        current_max_wear = float(filter_conf.get('max_paintwear', '1'))
        current_exterior = self.task.get('exterior', '')
        
        # 根据外观类型获取对应的磨损区间
        try:
            category = None
            # 根据外观名称匹配外观类型
            for cat in WearCategory:
                if WEAR_CATEGORY_NAMES[cat] == current_exterior:
                    category = cat
                    break
                    
            if category:
                # 获取该外观类型下的所有磨损区间
                wear_ranges = get_wear_ranges(category)
                current_range = None
                
                # 添加所有磨损区间到下拉框
                for wear_range in wear_ranges:
                    self.wear_combo.addItem(wear_range.show_name, wear_range)
                    # 检查是否是当前选中的区间
                    if abs(wear_range.min_val - current_min_wear) < 0.001 and abs(wear_range.max_val - current_max_wear) < 0.001:
                        current_range = wear_range
                        
                # 如果找到当前区间，设置为选中状态
                if current_range:
                    index = self.wear_combo.findText(current_range.show_name)
                    if index >= 0:
                        self.wear_combo.setCurrentIndex(index)
        except Exception as e:
            print(f"加载磨损区间失败: {str(e)}")
            
        wear_layout.addWidget(wear_label)
        wear_layout.addWidget(self.wear_combo)
        wear_layout.addStretch()
        info_layout.addLayout(wear_layout)
        
        layout.addLayout(info_layout)
        
        # 分析数据展示
        analysis_layout = QVBoxLayout()
        analysis_label = QLabel("分析数据：")
        analysis_label.setStyleSheet("font-size: 14px; font-weight: bold;")
        analysis_layout.addWidget(analysis_label)
        
        # 创建分析数据内容标签
        analysis_content = QLabel()
        analysis_content.setWordWrap(True)  # 允许文字换行
        analysis_content.setStyleSheet("""
            QLabel {
                font-size: 12px;
                background-color: #f5f5f5;
                border-radius: 4px;
                padding: 8px;
                color: #666;
                line-height: 1.4;
            }
        """)
        
        # 格式化分析数据
        def format_float(value, default="暂无"):
            if isinstance(value, dict):
                value = value.get('total_score')
            return f"{value:.2f}" if value is not None else default
            
        # 获取扫货记录分析数据
        analysis_data = None
        try:
            price_analysis_str = self.task.get('price_analysis', '{}')
            analysis_data = json.loads(price_analysis_str) if isinstance(price_analysis_str, str) else price_analysis_str
        except (json.JSONDecodeError, TypeError):
            pass
            
        analysis_text = ""
        if analysis_data and analysis_data.get('analysis_time'):
            # 格式化分析时间
            analysis_time = analysis_data['analysis_time']
            if isinstance(analysis_time, str):
                from datetime import datetime
                try:
                    analysis_time = datetime.fromisoformat(analysis_time.replace('Z', '+00:00'))
                except:
                    try:
                        analysis_time = datetime.strptime(analysis_time, '%Y-%m-%d %H:%M:%S')
                    except:
                        pass
            
            if hasattr(analysis_time, 'strftime'):
                analysis_time = analysis_time.strftime('%y-%m-%d %H:%M:%S')
            
            # 构建分析文本
            lines = []
            # lines.append(f"建议捡漏价: {format_float(self.task.get('suggested_snipe_price'))}元")
            
            # theoretical_price = self.task.get('theoretical_max_buy_price')
            # if theoretical_price is not None:
            #     lines.append(f"理论捡漏价：{theoretical_price:.2f}元")
            # else:
            #     lines.append("理论捡漏价：暂无")
                
            # lines.append(f"目标售价: {format_float(self.task.get('target_sell_price'))}元")
            
            # 添加扫货记录分析数据
            lines.append(f"扫货记录分析:{analysis_time}")
            
            # 添加统计数量
            if analysis_data.get('record_count') is not None:
                lines.append(f"统计数量：{analysis_data['record_count']}条")
            
            # 异常低价
            if analysis_data.get('abnormal_prices'):
                abnormal_prices_list = []
                for item in analysis_data['abnormal_prices']:
                    price = item['price']
                    count = item['count']
                    profit_rate = item.get('profit_rate', 0)
                    abnormal_prices_list.append(f"{price}元({count}次, {profit_rate:.1f}%)")
                lines.append(f"异常低价：{', '.join(abnormal_prices_list)}")
            else:
                lines.append("异常低价：无")
                
            # 最多售卖价
            if analysis_data.get('top_price_list'):
                top_prices = json.loads(analysis_data['top_price_list']) if isinstance(analysis_data['top_price_list'], str) else analysis_data['top_price_list']
                if top_prices:
                    top_prices_list = []
                    for price_info in top_prices:
                        price = price_info.get('price', 0)
                        count = price_info.get('count', 0)
                        top_prices_list.append(f"{price}元({count}次)")
                    lines.append(f"最多售卖价：{', '.join(top_prices_list)}")
                
            # 历史最低价
            if analysis_data.get('historical_low'):
                lines.append(f"历史最低价：{analysis_data['historical_low']:.2f}元")
                
            # 普通售价
            if analysis_data.get('normal_price'):
                lines.append(f"普通售价：{analysis_data['normal_price']:.2f}元")
                
            # 常见售价
            if analysis_data.get('common_sell_price'):
                lines.append(f"常见售价：{analysis_data['common_sell_price']:.2f}元")
                
            # 在售数量
            if analysis_data.get('selling_count'):
                lines.append(f"在售数量：{analysis_data['selling_count']}")
                
            # 添加投资评分信息
            # score_text = (
            #     f"投资评分: {format_float(self.task.get('score'))}  "
            #     f"流动性: {format_float(self.task.get('liquidity_score'))}  "
            #     f"价格优势: {format_float(self.task.get('price_advantage_score'))}\n"
            #     f"稳定性: {format_float(self.task.get('stability_score'))}  "
            #     f"供需评分: {format_float(self.task.get('supply_score'))}  "
            #     f"日均成交: {format_float(self.task.get('daily_volume'))}件"
            # )
            # lines.append(score_text)
            
            # 商品信息
            item_info = (
                f"磨损: {self.task.get('wear', '暂无')}  "
                f"稀有度: {self.task.get('rarity', '暂无')}  "
                f"品质: {self.task.get('quality', '暂无')}  "
                f"外观: {self.task.get('exterior', '暂无')}"
            )
            lines.append(item_info)
            
            analysis_text = '\n'.join(lines)
        else:
            # 如果没有扫货记录分析数据，则使用原有格式
            score_text = (
                f"投资评分: {format_float(self.task.get('score'))}  "
                f"流动性: {format_float(self.task.get('liquidity_score'))}  "
                f"价格优势: {format_float(self.task.get('price_advantage_score'))}\n"
                f"稳定性: {format_float(self.task.get('stability_score'))}  "
                f"供需评分: {format_float(self.task.get('supply_score'))}  "
                f"日均成交: {format_float(self.task.get('daily_volume'))}件\n"
            )
            
            # 解析历史价格范围
            historical_price = {}
            try:
                historical_price_str = self.task.get('historical_price_range', '{}')
                historical_price = json.loads(historical_price_str) if isinstance(historical_price_str, str) else historical_price_str
            except (json.JSONDecodeError, TypeError):
                pass
                
            # 解析价格趋势
            trend_data = {}
            try:
                trend_str = self.task.get('trend_analysis', '{}')
                trend_data = json.loads(trend_str) if isinstance(trend_str, str) else trend_data
            except (json.JSONDecodeError, TypeError):
                pass
                
            def format_trend(value):
                if value is None:
                    return "暂无"
                return f"+{value:.2f}" if value > 0 else f"{value:.2f}"
            
            # 确保historical_price和trend_data是字典，并且有默认值
            historical_price = historical_price or {}
            trend_data = trend_data or {}
                
            price_text = (
                f"历史最低价: {format_float(historical_price.get('lowest_price'))}元  "
                f"历史最高价: {format_float(historical_price.get('highest_price'))}元\n"
                f"整体趋势: {format_trend(trend_data.get('overall_trend'))}  "
                f"最近趋势: {format_trend(trend_data.get('recent_trend'))}\n"
            )
            
            item_info = (
                f"磨损: {self.task.get('wear', '暂无')}  "
                f"稀有度: {self.task.get('rarity', '暂无')}  "
                f"品质: {self.task.get('quality', '暂无')}\n"
                f"外观: {self.task.get('exterior', '暂无')}"
            )
            
            theoretical_price = self.task.get('theoretical_max_buy_price')
            if theoretical_price is not None:
                theoretical_price_text = f"理论捡漏价：{theoretical_price:.2f}"
            else:
                theoretical_price_text = "理论捡漏价：-"
            
            analysis_text = (
                f"建议捡漏价: {format_float(self.task.get('suggested_snipe_price'))}元\n"
                f"{theoretical_price_text}\n"
                f"目标售价: {format_float(self.task.get('target_sell_price'))}元\n"
                f"{score_text}\n{price_text}\n{item_info}"
            )
            
        analysis_content.setText(analysis_text)
        analysis_layout.addWidget(analysis_content)
        
        layout.addLayout(analysis_layout)
        
        # 可编辑字段
        edit_layout = QVBoxLayout()
        edit_layout.setObjectName("edit_layout")  # 添加对象名称，便于后续查找
        
        # 扫货定价类型
        pricing_type_layout = QHBoxLayout()
        pricing_type_label = QLabel("扫货定价类型：")
        pricing_type_label.setStyleSheet("font-size: 14px;")
        self.pricing_type_combo = QComboBox()
        self.pricing_type_combo.addItem("固定价格", 0)
        self.pricing_type_combo.addItem("动态利润率", 1)
        self.pricing_type_combo.addItem("固定利润率", 2)
        self.pricing_type_combo.setStyleSheet("""
            QComboBox {
                padding: 5px;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                font-size: 14px;
                min-width: 150px;
            }
            QComboBox:hover {
                border-color: #40a9ff;
            }
        """)
        self.pricing_type_combo.currentIndexChanged.connect(self.on_pricing_type_changed)
        pricing_type_layout.addWidget(pricing_type_label)
        pricing_type_layout.addWidget(self.pricing_type_combo)
        price_frame_layout = QVBoxLayout()
        price_frame_layout.setContentsMargins(10, 10, 10, 10)
        price_frame_layout.setSpacing(10)
        price_frame_layout.addLayout(pricing_type_layout)
        
        # 固定价格输入框
        self.fixed_price_container = QWidget()
        fixed_price_layout = QHBoxLayout(self.fixed_price_container)
        fixed_price_layout.setContentsMargins(0, 0, 0, 0)
        fixed_price_label = QLabel("捡漏价：")
        fixed_price_label.setStyleSheet("font-size: 14px;")
        self.price_input = QLineEdit()
        self.price_input.setText(str(self.task['buy_price_limit']) if self.task.get('buy_price_limit') is not None else '')
        self.price_input.setPlaceholderText("请输入捡漏价...")
        self.price_input.setStyleSheet("""
            QLineEdit {
                padding: 5px;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                font-size: 14px;
            }
            QLineEdit:focus {
                border-color: #40a9ff;
            }
        """)
        fixed_price_layout.addWidget(fixed_price_label)
        fixed_price_layout.addWidget(self.price_input)
        
        # 利润率输入框
        self.profit_rate_container = QWidget()
        profit_rate_layout = QHBoxLayout(self.profit_rate_container)
        profit_rate_layout.setContentsMargins(0, 0, 0, 0)
        profit_rate_label = QLabel("利润率：")
        profit_rate_label.setStyleSheet("font-size: 14px;")
        self.profit_rate_input = QLineEdit()
        
        # 正确处理利润率的显示，确保数据范围合理
        profit_rate = self.task.get('profit_rate', 0)
        # 确保利润率是一个合理的值
        if profit_rate is not None and isinstance(profit_rate, (int, float)):
            # 避免负数或异常大的值
            if profit_rate < 0:
                profit_rate = 0
            elif profit_rate > 99:
                profit_rate = 99
                
        print(f"显示利润率: {profit_rate}%")
        self.profit_rate_input.setText(f"{profit_rate:.2f}")
        self.profit_rate_input.setPlaceholderText("请输入利润率...")
        self.profit_rate_input.setStyleSheet("""
            QLineEdit {
                padding: 5px;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                font-size: 14px;
            }
            QLineEdit:focus {
                border-color: #40a9ff;
            }
        """)
        percent_label = QLabel("%")
        percent_label.setStyleSheet("font-size: 14px;")
        profit_rate_layout.addWidget(profit_rate_label)
        profit_rate_layout.addWidget(self.profit_rate_input)
        profit_rate_layout.addWidget(percent_label)
        
        # 扫货价输入框
        self.scan_price_container = QWidget()
        scan_price_layout = QHBoxLayout(self.scan_price_container)
        scan_price_layout.setContentsMargins(0, 0, 0, 0)
        scan_price_label = QLabel("扫货价：")
        scan_price_label.setStyleSheet("font-size: 14px;")
        self.scan_price_input = QLineEdit()
        
        # 获取任务数据中的扫货价
        buy_price_limit = self.task.get('buy_price_limit')
        
        # 确保扫货价是一个合理的值
        if buy_price_limit is None or not isinstance(buy_price_limit, (int, float)) or buy_price_limit <= 0:
            # 如果数据库中没有值或值不合理，提供一个默认值
            if self.task.get('target_sell_price') is not None and self.task.get('target_sell_price') > 0:
                # 默认扫货价为目标售价的80%
                buy_price_limit = self.task.get('target_sell_price') * 0.8
                print(f"扫货价无效，设置默认值为目标售价的80%: {buy_price_limit}")
            else:
                buy_price_limit = ""
        else:
            print(f"使用数据库中的扫货价: {buy_price_limit}")
        
        # 显示扫货价
        if buy_price_limit != "":
            self.scan_price_input.setText(f"{buy_price_limit:.2f}")
        else:
            self.scan_price_input.setText("")
            
        self.scan_price_input.setPlaceholderText("请输入扫货价...")
        self.scan_price_input.setStyleSheet("""
            QLineEdit {
                padding: 5px;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                font-size: 14px;
            }
            QLineEdit:focus {
                border-color: #40a9ff;
            }
        """)
        scan_price_layout.addWidget(scan_price_label)
        scan_price_layout.addWidget(self.scan_price_input)
        
        # 最低利润率输入框
        self.min_profit_rate_container = QWidget()
        min_profit_rate_layout = QHBoxLayout(self.min_profit_rate_container)
        min_profit_rate_layout.setContentsMargins(0, 0, 0, 0)
        min_profit_rate_label = QLabel("最低利润率：")
        min_profit_rate_label.setStyleSheet("font-size: 14px;")
        self.min_profit_rate_input = QLineEdit()
        
        # 获取任务数据中的最低利润率
        min_profit_rate = self.task.get('min_profit_rate', 0)
        
        # 确保最低利润率是一个合理的值
        if min_profit_rate is not None and isinstance(min_profit_rate, (int, float)):
            # 避免负数或异常大的值
            if min_profit_rate < 0:
                min_profit_rate = 0
            elif min_profit_rate > 99:
                min_profit_rate = 99
                
        print(f"显示最低利润率: {min_profit_rate}%")
        self.min_profit_rate_input.setText(f"{min_profit_rate:.2f}")
        self.min_profit_rate_input.setPlaceholderText("请输入最低利润率...")
        self.min_profit_rate_input.setStyleSheet("""
            QLineEdit {
                padding: 5px;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                font-size: 14px;
            }
            QLineEdit:focus {
                border-color: #40a9ff;
            }
        """)
        min_percent_label = QLabel("%")
        min_percent_label.setStyleSheet("font-size: 14px;")
        min_profit_rate_layout.addWidget(min_profit_rate_label)
        min_profit_rate_layout.addWidget(self.min_profit_rate_input)
        min_profit_rate_layout.addWidget(min_percent_label)
        
        # 添加四个容器到价格框架中
        price_frame_layout.addWidget(self.fixed_price_container)
        price_frame_layout.addWidget(self.profit_rate_container)
        price_frame_layout.addWidget(self.scan_price_container)
        price_frame_layout.addWidget(self.min_profit_rate_container)
        
        # 创建一个带边框的框架来包含价格设置
        price_frame = QFrame()
        price_frame.setFrameShape(QFrame.Shape.Box)
        price_frame.setFrameShadow(QFrame.Shadow.Sunken)
        price_frame.setStyleSheet("""
            QFrame {
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                background-color: #fafafa;
            }
        """)
        price_frame.setLayout(price_frame_layout)
        
        edit_layout.addWidget(price_frame)
        
        # 购买数量
        quantity_layout = QHBoxLayout()
        quantity_label = QLabel("购买数量：")
        quantity_label.setStyleSheet("font-size: 14px;")
        self.quantity_input = QLineEdit()
        self.quantity_input.setText(str(self.task['buy_num_limit']))  
        self.quantity_input.setPlaceholderText("请输入购买数量...")
        self.quantity_input.setStyleSheet("""
            QLineEdit {
                padding: 5px;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                font-size: 14px;
            }
            QLineEdit:focus {
                border-color: #40a9ff;
            }
        """)
        quantity_layout.addWidget(quantity_label)
        quantity_layout.addWidget(self.quantity_input)
        edit_layout.addLayout(quantity_layout)
        
        layout.addLayout(edit_layout)
        
        # 按钮
        btn_layout = QHBoxLayout()
        btn_layout.addStretch()
        
        # 取消按钮
        cancel_btn = QPushButton("取消")
        cancel_btn.setFixedSize(80, 32)
        cancel_btn.setStyleSheet("""
            QPushButton {
                background-color: white;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                color: rgba(0, 0, 0, 0.85);
                font-size: 14px;
            }
            QPushButton:hover {
                border-color: #40a9ff;
                color: #40a9ff;
            }
            QPushButton:pressed {
                background-color: #fafafa;
            }
        """)
        cancel_btn.clicked.connect(self.reject)
        
        # 更新按钮
        update_btn = QPushButton("更新")
        update_btn.setFixedSize(80, 32)
        update_btn.setStyleSheet("""
            QPushButton {
                background-color: #1890ff;
                border: none;
                border-radius: 4px;
                color: white;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #40a9ff;
            }
            QPushButton:pressed {
                background-color: #096dd9;
            }
        """)
        update_btn.clicked.connect(self.on_update)
        
        btn_layout.addWidget(cancel_btn)
        btn_layout.addWidget(update_btn)
        
        layout.addLayout(btn_layout)
        
        # 设置初始选项和初始联动显示
        # 注意：必须在所有组件都创建完成后设置，且需要断开信号连接，避免重复触发事件
        try:
            # 确保正确获取pricing_type，尝试多种可能的访问方式
            pricing_type = 0  # 默认值
            if isinstance(self.task, dict):
                pricing_type = self.task.get('pricing_type', 0)
            else:
                # 如果是数据库对象
                pricing_type = getattr(self.task, 'pricing_type', 0)
            
            # 确保值在有效范围内
            if pricing_type not in [0, 1, 2]:
                pricing_type = 0
                
            # 设置下拉框选项
            self.pricing_type_combo.blockSignals(True)
            self.pricing_type_combo.setCurrentIndex(pricing_type)
            self.pricing_type_combo.blockSignals(False)
            
            # 手动触发联动显示
            self.on_pricing_type_changed(pricing_type)
            
            print(f"设置初始定价类型: {pricing_type}")  # 调试信息
        except Exception as e:
            print(f"设置初始定价类型出错: {str(e)}")  # 调试信息
            # 出错时使用默认值
            self.pricing_type_combo.setCurrentIndex(0)
            self.on_pricing_type_changed(0)
    
    def on_pricing_type_changed(self, index):
        """处理定价方式变化"""
        # 根据选择的定价类型显示/隐藏对应的输入框
        if index == 0:  # 固定价格
            self.fixed_price_container.setVisible(True)
            self.profit_rate_container.setVisible(False)
            self.scan_price_container.setVisible(False)
            self.min_profit_rate_container.setVisible(False)
        elif index == 1:  # 动态利润率
            self.fixed_price_container.setVisible(False)
            self.profit_rate_container.setVisible(True)
            self.scan_price_container.setVisible(True)
            self.min_profit_rate_container.setVisible(True)
        else:  # 固定利润率
            self.fixed_price_container.setVisible(False)
            self.profit_rate_container.setVisible(True)
            self.scan_price_container.setVisible(True)
            self.min_profit_rate_container.setVisible(False)
            
        # 确保利润率和扫货价显示数据库中的值
        # 处理利润率显示
        profit_rate = self.task.get('profit_rate', 0)
        if profit_rate is not None and isinstance(profit_rate, (int, float)):
            # 避免负数或异常大的值
            if profit_rate < 0:
                profit_rate = 0
            elif profit_rate > 99:
                profit_rate = 99
            print(f"切换到利润率定价，显示任务利润率: {profit_rate}%")
            self.profit_rate_input.setText(f"{profit_rate:.2f}")
        
        # 处理扫货价显示
        buy_price_limit = self.task.get('buy_price_limit')
        if buy_price_limit is not None and isinstance(buy_price_limit, (int, float)) and buy_price_limit > 0:
            print(f"切换到利润率定价，显示任务扫货价: {buy_price_limit}")
            self.scan_price_input.setText(f"{buy_price_limit:.2f}")
    
    def on_profit_rate_changed(self):
        """处理利润率变化"""
        if self.task.get('target_sell_price') is not None and self.task.get('target_sell_price') > 0 and not self.is_updating_scan_price:
            try:
                # 获取输入文本
                text = self.profit_rate_input.text().strip()
                if not text:  # 如果文本为空，不执行计算
                    return
                    
                # 尝试将输入转换为浮点数
                profit_rate = float(text) / 100
                
                # 验证利润率合理性
                if profit_rate < 0:
                    profit_rate = 0
                elif profit_rate > 0.99:
                    profit_rate = 0.99
                
                # 计算方式: 扫货价 = (1-当前输入的利润率)*目标售价
                target_sell_price = self.task.get('target_sell_price')
                if target_sell_price is None:
                    # 如果目标售价为None，则使用sell_min_price作为替代
                    target_sell_price = self.task.get('buy_price_limit', 0)
                
                scan_price = (1 - profit_rate) * target_sell_price
                
                # 验证扫货价合理性
                if scan_price <= 0:
                    scan_price = 0.01
                
                print(f"利润率变化: {profit_rate*100}% -> 扫货价: {scan_price}")
                
                # 避免递归更新
                self.is_updating_scan_price = True
                self.scan_price_input.setText(f"{scan_price:.2f}")
                self.is_updating_scan_price = False
            except ValueError:
                print(f"利润率输入无效: {self.profit_rate_input.text()}")
    
    def on_scan_price_changed(self):
        """处理扫货价变化"""
        if self.task.get('target_sell_price') is not None and self.task.get('target_sell_price') > 0 and not self.is_updating_profit_rate:
            try:
                # 获取输入文本
                text = self.scan_price_input.text().strip()
                if not text:  # 如果文本为空，不执行计算
                    return
                    
                # 尝试将输入转换为浮点数
                scan_price = float(text)
                
                # 验证扫货价合理性
                if scan_price <= 0:
                    scan_price = 0.01
                elif scan_price >= self.task.get('target_sell_price'):
                    scan_price = self.task.get('target_sell_price') * 0.99
                
                # 计算方式: 利润率 = (目标售价-当前输入的扫货价)/目标售价
                profit_rate = (self.task.get('target_sell_price') - scan_price) / self.task.get('target_sell_price')
                
                # 验证利润率合理性
                if profit_rate < 0:
                    profit_rate = 0
                elif profit_rate > 0.99:
                    profit_rate = 0.99
                
                profit_rate_display = profit_rate * 100
                print(f"扫货价变化: {scan_price} -> 利润率: {profit_rate_display}%")
                
                # 避免递归更新
                self.is_updating_profit_rate = True
                self.profit_rate_input.setText(f"{profit_rate_display:.2f}")
                self.is_updating_profit_rate = False
            except ValueError:
                print(f"扫货价输入无效: {self.scan_price_input.text()}")
                
    def keyPressEvent(self, event):
        """处理键盘事件"""
        # 检查是否按下回车键
        if event.key() == Qt.Key.Key_Return or event.key() == Qt.Key.Key_Enter:
            # 先获取当前焦点对象
            focus_widget = QApplication.focusWidget()
            
            # 根据焦点对象决定计算方向
            if focus_widget == self.profit_rate_input:
                self.on_profit_rate_changed()
                # 阻止事件传递，防止触发默认按钮
                event.accept()
                return
            elif focus_widget == self.scan_price_input:
                self.on_scan_price_changed()
                # 阻止事件传递，防止触发默认按钮
                event.accept()
                return
        
        # 其他情况继续传递事件给父类
        super().keyPressEvent(event)
    
    def calculate_prices(self):
        """计算价格按钮的处理函数 - 已禁用，保留方法为了兼容性"""
        pass  # 不执行任何操作
    
    def on_update(self):
        """更新任务"""
        try:
            # 获取输入值
            pricing_type = self.pricing_type_combo.currentIndex()
            
            # 初始化变量
            buy_price_limit = None
            min_profit_rate = None
            
            if pricing_type == 0:  # 固定价格
                # 从固定价格输入框获取价格
                try:
                    buy_price_limit = float(self.price_input.text()) if self.price_input.text() else None
                    if buy_price_limit is not None and buy_price_limit <= 0:
                        QMessageBox.warning(self, "错误", "捡漏价必须大于0")
                        return
                except ValueError:
                    QMessageBox.warning(self, "错误", "请输入有效的捡漏价")
                    return
                    
                # 固定价格模式下，保留数据库中原有的利润率
                profit_rate = self.task.get('profit_rate', 0)
                print(f"固定价格模式：保留原有利润率 {profit_rate}")
            else:  # 固定利润率或动态利润率
                # 处理利润率
                try:
                    profit_rate_text = self.profit_rate_input.text().strip()
                    if profit_rate_text:
                        # 直接使用输入的百分比值，不需要除以100
                        profit_rate = float(profit_rate_text)
                        # 确保利润率在合理范围内
                        profit_rate = max(0, min(profit_rate, 99))
                    
                    if profit_rate <= 0:
                        QMessageBox.warning(self, "错误", "利润率必须大于0")
                        return
                except ValueError:
                    QMessageBox.warning(self, "错误", "请输入有效的利润率")
                    return
                
                # 处理扫货价
                try:
                    buy_price_limit_text = self.scan_price_input.text().strip()
                    if buy_price_limit_text:
                        buy_price_limit = float(buy_price_limit_text)
                        # 确保扫货价在合理范围内
                        if self.task.get('target_sell_price') > 0:
                            # 扫货价不应该大于目标售价
                            buy_price_limit = min(buy_price_limit, self.task.get('target_sell_price') * 0.99)
                        buy_price_limit = max(0.01, buy_price_limit)  # 至少1分钱
                    
                    if buy_price_limit is None or buy_price_limit <= 0:
                        QMessageBox.warning(self, "错误", "扫货价必须大于0")
                        return
                except ValueError:
                    QMessageBox.warning(self, "错误", "请输入有效的扫货价")
                    return
                
                # 处理最低利润率（仅当选择动态利润率时）
                if pricing_type == 1:  # 动态利润率
                    try:
                        min_profit_rate_text = self.min_profit_rate_input.text().strip()
                        if min_profit_rate_text:
                            min_profit_rate = float(min_profit_rate_text)
                            # 确保最低利润率在合理范围内
                            min_profit_rate = max(0, min(min_profit_rate, 99))
                            
                            # 确保最低利润率不大于当前利润率
                            if min_profit_rate > profit_rate:
                                QMessageBox.warning(self, "错误", "最低利润率不能大于当前利润率")
                                return
                    except ValueError:
                        QMessageBox.warning(self, "错误", "请输入有效的最低利润率")
                        return
            
            # 获取购买数量
            try:
                quantity = int(self.quantity_input.text()) if self.quantity_input.text() else None
                if quantity is not None and quantity <= 0:
                    QMessageBox.warning(self, "错误", "购买数量必须大于0")
                    return
            except ValueError:
                QMessageBox.warning(self, "错误", "请输入有效的购买数量")
                return
            
            # 获取当前选中的磨损度
            current_wear_range = self.wear_combo.currentData()
            if current_wear_range:
                min_wear = current_wear_range.min_val
                max_wear = current_wear_range.max_val
            else:
                min_wear = None
                max_wear = None
            
            # 打印调试信息
            print(f"保存任务数据 - 定价类型: {pricing_type}, 目标售价: {self.task.get('target_sell_price')}, 利润率: {profit_rate}, 扫货价: {buy_price_limit}, 最低利润率: {min_profit_rate}")
            
            # 更新任务参数
            update_params = {
                'task_id': self.task.get('id'),
                'buy_price_limit': buy_price_limit,
                'pricing_type': pricing_type,
                'profit_rate': profit_rate,  # 直接使用百分比值（100分制）
                'buy_num_limit': quantity,
                'min_profit_rate': min_profit_rate  # 添加最低利润率参数
            }
            
            # 如果有磨损值参数，添加到更新参数中
            if min_wear is not None:
                update_params['min_paintwear'] = min_wear
            if max_wear is not None:
                update_params['max_paintwear'] = max_wear
                
            # 移除None值
            update_params = {k: v for k, v in update_params.items() if v is not None}
            
            # 更新任务
            if self.task_manager.update_task(**update_params):
                print(f"任务[{self.task['id']}]更新成功, 扫货价: {buy_price_limit}, 利润率: {profit_rate}%")
                
                # 检查是否修改了利润率、扫货价格或扫货定价类型
                original_profit_rate = self.task.get('profit_rate')
                original_buy_price = self.task.get('buy_price_limit')
                original_pricing_type = self.task.get('pricing_type')
                
                # 如果有修改，则添加一条人为调整的记录
                if (profit_rate != original_profit_rate or 
                    buy_price_limit != original_buy_price or 
                    pricing_type != original_pricing_type):
                    
                    # 获取任务的目标售价
                    target_sell_price = self.task.get('target_sell_price')
                    
                    # 添加人为调整记录
                    self.add_profit_rate_price_record(
                        goods_id=self.task.get('goods_id'),
                        goods_name=self.task.get('name', ''),
                        hash_name=self.task.get('hash_name', ''),
                        profit_rate=profit_rate,
                        buy_price=buy_price_limit,
                        target_sell_price=target_sell_price,
                        pricing_type=pricing_type   # 界面索引从0开始，数据库从1开始
                    )
                
                self.accept()  # 关闭对话框
            else:
                QMessageBox.warning(self, "错误", "任务更新失败")
        except Exception as e:
            QMessageBox.warning(self, "错误", f"发生错误: {str(e)}")
    
    def add_profit_rate_price_record(self, goods_id, goods_name, hash_name, profit_rate, buy_price, target_sell_price, pricing_type):
        """添加利润率价格变动记录"""
        record_data = {
            'goods_id': goods_id,
            'goods_name': goods_name,
            'hash_name': hash_name,
            'profit_rate': profit_rate,
            'buy_price': buy_price,
            'target_sell_price': target_sell_price,
            'operator': 'user',  # 操作人为用户
            'remark': '人为调整 - 任务编辑',
            'modify_type': 2,  # 2: 人为调整
            'pricing_type': pricing_type  # 已在调用处进行了转换
        }
        
        # 添加记录
        self.profit_rate_price_manager.add_record(record_data)
        print(f"已添加利润率价格变动记录: 商品ID={goods_id}, 利润率={profit_rate}, "
              f"扫货价={buy_price}, 目标售价={target_sell_price}")
